package br.urca.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import br.urca.dao.ProtocoloDAO;
import br.urca.model.Protocolo;

public class JPAProtocoloDAO implements ProtocoloDAO {

	private final EntityManager manager;
	
	public JPAProtocoloDAO() {
		this(null);
	}
	
	@Inject
	public JPAProtocoloDAO(EntityManager manager) {
		this.manager = manager;
	}

	@Override
	public Protocolo getRegistro(String numero, String periodo) {
		try {
			return this.manager
					.createQuery(
							"SELECT p FROM Protocolo p "
									+ "WHERE p.id.numero = :numero "
									+ "AND p.id.periodo = :periodo ",
									Protocolo.class)
					.setParameter("numero", numero)
					.setParameter("periodo", periodo)
					.getSingleResult();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public String ProximoNumero(String periodo) {
		try {
			List<String> mList =  this.manager
					.createQuery(
							"SELECT p.id.numero FROM Protocolo p "
									+ "WHERE p.id.periodo = :periodo "
									+ "ORDER BY p.id.numero",
									String.class)
					.setParameter("periodo", periodo)					
					.getResultList();
			
			int cod = 0;
			if (mList != null) { 
				cod = Integer.valueOf(mList.get(mList.size() - 1));
			}	
			cod++;
			return formatCodigo(String.valueOf(cod));
		} catch (Exception e) {
			return null;
		}
	}
	
	@Override
	public boolean salvarProtocolo(Protocolo protocolo) {		
		return this.manager.merge(protocolo) != null;
	}
	
	private String formatCodigo(String numero) {
		String aux = "";		
		switch (numero.length()) {
			case 1:
				aux = "0000".concat(numero);
				break;
			case 2:
				aux = "000".concat(numero);
				break;
			case 3:
				aux = "00".concat(numero);
				break;
			case 4:
				aux = "0".concat(numero);
				break;
			case 5:
				aux = numero;
				break;	
		}	
		return aux;
	}


}
